import { defineStore } from 'pinia';
import { store } from '/@/store';
import type { Project } from '/#/store';

import {
  TENANTID_KEY,
  DOMAIN_KEY,
  PROJECTINFO_KEY,
  USER_CONFIG_KEY,
  REMEMBERME_KEY,
} from '/@/enums/cacheEnum';
import { createLocalStorage } from '/@/utils/cache';

const ls = createLocalStorage();
const domainSetting = ls.get(DOMAIN_KEY) || '';
const tenantID = ls.get(TENANTID_KEY) || '';
const projectSetting = ls.get(PROJECTINFO_KEY) || {
  title: '',
  icon: '',
  logo: '',
  logo2: '',
};
const userConfig = ls.get(USER_CONFIG_KEY) || {
  account: '',
  password: '',
};

const rememberMe = ls.get(REMEMBERME_KEY) || false;

interface UserConfig {
  account: string;
  password: string;
}
interface DomainConfig {
  rememberMe: boolean;
  userConfig: UserConfig | null;
  domain: string;
  tenantId: string;
  projectInfo: Project;
}

interface DomainState {
  domainInfo: DomainConfig;
}

export const useDomainStore = defineStore({
  id: 'app-domain',
  state: (): DomainState => ({
    domainInfo: {
      rememberMe,
      userConfig,
      tenantId: tenantID,
      domain: domainSetting,
      projectInfo: projectSetting,
    },
  }),
  getters: {
    getrRememberMe(): boolean {
      return this.domainInfo.rememberMe;
    },
    getUseConfig(): UserConfig | null {
      return this.domainInfo.userConfig;
    },
    getDomain(): string {
      return this.domainInfo?.domain ?? '';
    },
    getTenantId(): string {
      return this.domainInfo?.tenantId ?? '';
    },
    getProjectInfo(): Project {
      return this.domainInfo.projectInfo;
    },
  },
  actions: {
    setUser(user) {
      this.domainInfo.userConfig = Object.assign({}, this.domainInfo.userConfig, user);
      ls.set(USER_CONFIG_KEY, user);
    },
    setRememberMe(rememberMe) {
      this.domainInfo = { ...this.domainInfo, rememberMe };
      ls.set(REMEMBERME_KEY, rememberMe);
    },
    setProjectInfo(projectInfo) {
      this.domainInfo.projectInfo = Object.assign({}, this.domainInfo.projectInfo, projectInfo);
      ls.set(PROJECTINFO_KEY, projectInfo);
    },
    setDomainInfo(domain) {
      this.domainInfo = { ...this.domainInfo, domain };
      ls.set(DOMAIN_KEY, domain);
    },
    setTenantId(tenantId) {
      this.domainInfo = { ...this.domainInfo, tenantId };

      ls.set(TENANTID_KEY, tenantId);
    },
  },
});

export function useDomainStoreWithOut() {
  return useDomainStore(store);
}
